from django.core.paginator import Paginator
from django.shortcuts import render, HttpResponse, get_object_or_404, redirect
from django.views.decorators.csrf import csrf_exempt
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from .models import Document, DocumentCategory, DocumentVersion
from django.http import JsonResponse
import json

@login_required
def document_list(request):
    documents = Document.objects.all().order_by('-created_at')
    categories = DocumentCategory.objects.all()
    
    # 搜索过滤
    search_query = request.GET.get('search', '')
    if search_query:
        documents = documents.filter(title__icontains=search_query)
    
    # 分类过滤
    category_id = request.GET.get('category')
    if category_id:
        documents = documents.filter(category_id=category_id)
    
    # 状态过滤
    status_filter = request.GET.get('status')
    if status_filter:
        documents = documents.filter(status=status_filter)
    
    paginator = Paginator(documents, 10)
    page_number = request.GET.get('page')
    page_obj = paginator.get_page(page_number)
    
    context = {
        'page_obj': page_obj,
        'categories': categories,
        'search_query': search_query,
        'selected_category': int(category_id) if category_id else None,
        'selected_status': status_filter
    }
    return render(request, 'doc_manager/document_list.html', context)

from django.core.exceptions import ValidationError
from django.http import JsonResponse
from django.views.decorators.http import require_http_methods
import requests
import json

def classify_document(content):
    """
    调用AI API对文档内容进行分类
    返回分类结果字符串
    """
    try:
        # 这里使用模拟API调用，实际项目中应替换为真实API
        # 示例使用简单的关键词匹配进行分类
        content = content.lower()
        if any(word in content for word in ['财务', '会计', '预算']):
            return 'finance'
        elif any(word in content for word in ['合同', '法律', '条款']):
            return 'legal'
        elif any(word in content for word in ['招聘', '员工', '培训']):
            return 'hr'
        elif any(word in content for word in ['技术', '代码', '开发']):
            return 'tech'
        elif any(word in content for word in ['市场', '销售', '推广']):
            return 'marketing'
        else:
            return 'other'
    except Exception:
        return 'other'

@login_required
def document_detail(request, pk):
    document = get_object_or_404(Document, pk=pk)
    versions = document.versions.all().order_by('-version_number')
    return render(request, 'doc_manager/document_detail.html', {
        'document': document,
        'versions': versions
    })

@login_required
def document_create(request):
    if request.method == 'POST':
        try:
            title = request.POST.get('title')
            content = request.POST.get('content', '')
            file = request.FILES.get('file')
            category_id = request.POST.get('category')
            status = request.POST.get('status', 'draft')
            tags = request.POST.get('tags', '')
            description = request.POST.get('description', '')
            
            document = Document(
                title=title,
                content=content,
                file=file,
                category_id=category_id,
                status=status,
                created_by=request.user,
                tags=tags,
                description=description
            )
            document.save()
            
            messages.success(request, '文档创建成功')
            return redirect('document_detail', pk=document.id)
        except Exception as e:
            messages.error(request, f'文档创建失败: {str(e)}')
            return redirect('document_list')
    
    categories = DocumentCategory.objects.all()
    return render(request, 'doc_manager/document_form.html', {
        'categories': categories,
        'form_action': 'create'
    })

@login_required
def document_update(request, pk):
    document = get_object_or_404(Document, pk=pk)
    
    if request.method == 'POST':
        try:
            document.title = request.POST.get('title', document.title)
            document.content = request.POST.get('content', document.content)
            document.category_id = request.POST.get('category', document.category_id)
            document.status = request.POST.get('status', document.status)
            document.tags = request.POST.get('tags', document.tags)
            document.description = request.POST.get('description', document.description)
            
            if 'file' in request.FILES:
                document.file = request.FILES['file']
            
            document.save()
            
            messages.success(request, '文档更新成功')
            return redirect('document_detail', pk=document.id)
        except Exception as e:
            messages.error(request, f'文档更新失败: {str(e)}')
            return redirect('document_list')
    
    categories = DocumentCategory.objects.all()
    return render(request, 'doc_manager/document_form.html', {
        'document': document,
        'categories': categories,
        'form_action': 'update'
    })

@login_required
def document_delete(request, pk):
    document = get_object_or_404(Document, pk=pk)
    if request.method == 'POST':
        document.delete()
        messages.success(request, '文档删除成功')
        return redirect('document_list')
    return render(request, 'doc_manager/document_confirm_delete.html', {'document': document})

@require_http_methods(["POST"])
@csrf_exempt
def document_upload(request):
    if request.method == 'POST':
        try:
            file = request.FILES.get('file')
            title = request.POST.get('title')
            version = request.POST.get('version', '1.0')
            
            if not all([file, title]):
                return JsonResponse({'status': 'error', 'message': '缺少必要参数'}, status=400)
            
            # 读取文件内容进行AI分类
            file_content = file.read().decode('utf-8', errors='ignore')[:10000]  # 限制前10000字符
            category = classify_document(file_content)
            
            # 自动检测文档类型
            file_ext = file.name.split('.')[-1].lower()
            doc_type = 'other'
            if file_ext in ['pdf']:
                doc_type = 'pdf'
            elif file_ext in ['doc', 'docx']:
                doc_type = 'doc'
            elif file_ext in ['xls', 'xlsx']:
                doc_type = 'xls'
            elif file_ext in ['ppt', 'pptx']:
                doc_type = 'ppt'
            elif file_ext in ['jpg', 'jpeg', 'png']:
                doc_type = 'img'
            
            document = Document(
                title=title,
                file=file,
                doc_type=doc_type,
                version=version,
                category=category
            )
            
            # 触发模型验证
            document.full_clean()
            document.save()
            
            return JsonResponse({'status': 'success', 'id': document.id})
        except ValidationError as e:
            return JsonResponse({'status': 'error', 'message': '\n'.join(e.messages)}, status=400)
        except Exception as e:
            return JsonResponse({'status': 'error', 'message': str(e)}, status=400)
